#include "page3.h"          // 设备查询
#include "ui_page3.h"
#include<QSqlTableModel>
#include<QFileDialog>
#include<QTextStream>
#include<QMenu>
#include"saveqrcode.h"
#include"src/mes.h"
#include<QMessageBox>
#include<QSqlError>
#include<QDebug>
#include<QClipboard>
#include<QTableWidgetItem>
#include<QDate>
#include"repairhistorydialog.h"
#include"checkhistorydialog.h"
#include"userchangedialog.h"
#include"usedialog.h"

Page3::Page3(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Page3)
{
    ui->setupUi(this);
}

Page3::Page3(int role,QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Page3)
{
    Q_UNUSED(role);
    ui->setupUi(this);
    initPopMenu();
    initPopMenu1();
    initPopMenu2();
    initUserRecordRead();

    QList<QString> itemList=Mes::getInstance()->getClassMap().keys();
    itemList.push_front("");
    ui->classCombox->addItems(QStringList(itemList));

    ui->dateCombox->addItem(QDate::currentDate().toString("yyyy年MM月dd日ddd"));
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);

    ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);      // 菜单策略
}
//    if(role==ADMIN){
////        ui->twoModelCombox->addItems(QStringList({"查询模式","修改模式"}));
//        ui->twoModelCombox->addItems(QStringList({"查询模式"}));
//    }else{
//        ui->twoModelCombox->addItems(QStringList({"查询模式"}));
////        ui->twoModelCombox->addItems(QStringList({"查询模式"}));
////        ui->modifyLayout->removeWidget(ui->modifyButton);
////        ui->modifyButton->setEnabled(false);
//    }


Page3::~Page3()
{
    delete ui;
}

void Page3::initTableWidget()
{
    tableData.clear();
    for(int row=ui->tableWidget->rowCount()-1;row>=0;row--){
        ui->tableWidget->removeRow(row);
    }

    if(Mes::getInstance()->getTableData(tableData,ui->checkClassCombox->currentText().trimmed(),
                                        ui->checkNameLine->text().trimmed())){
        QString checkStatus=ui->checkStatusCombox->currentText().trimmed();
        QString finishStatu=ui->finishStatusCombox->currentText().trimmed();
        QString workNumber=ui->checkWorkNubmer->text().trimmed();
        QString name=ui->checkName->text().trimmed();
        QString NO=ui->checkNo->text().trimmed();

        for(int i=0;i<tableData.size();i++){
            if(checkStatus!="" || finishStatu!="" || name!="" || NO!="" || workNumber!=""){
                if(!(tableData[i][6]==checkStatus || checkStatus=="") || !(tableData[i][8]==finishStatu ||
                        finishStatu=="") || !(tableData[i][2]==workNumber || workNumber=="") ||
                        !(tableData[i][1].contains(name,Qt::CaseInsensitive) || name=="") ||
                        !(tableData[i][0].contains(NO,Qt::CaseInsensitive) || NO=="")){
                    continue;
                }

                ui->tableWidget->insertRow(ui->tableWidget->rowCount());
                int rowIdx=ui->tableWidget->rowCount()-1;
                QTableWidgetItem *item0=new QTableWidgetItem(tableData[i][0]);
                QTableWidgetItem *item1=new QTableWidgetItem(tableData[i][1]);
                QTableWidgetItem *item2=new QTableWidgetItem(tableData[i][2]);
                QTableWidgetItem *item3=new QTableWidgetItem(tableData[i][3]);
                QTableWidgetItem *item4=new QTableWidgetItem(tableData[i][4]);
                QTableWidgetItem *item5=new QTableWidgetItem(tableData[i][5]);
                QTableWidgetItem *item6=new QTableWidgetItem(tableData[i][6]);
                QTableWidgetItem *item7=new QTableWidgetItem(tableData[i][7]);
                QTableWidgetItem *item8=new QTableWidgetItem(tableData[i][8]);
                ui->tableWidget->setItem(rowIdx,0,item0);
                ui->tableWidget->setItem(rowIdx,1,item1);
                ui->tableWidget->setItem(rowIdx,2,item2);
                ui->tableWidget->setItem(rowIdx,3,item3);
                ui->tableWidget->setItem(rowIdx,4,item4);
                ui->tableWidget->setItem(rowIdx,5,item5);
                ui->tableWidget->setItem(rowIdx,6,item6);
                ui->tableWidget->setItem(rowIdx,7,item7);
                ui->tableWidget->setItem(rowIdx,8,item8);
            }else{
                ui->tableWidget->insertRow(ui->tableWidget->rowCount());
                int rowIdx=ui->tableWidget->rowCount()-1;
                QTableWidgetItem *item0=new QTableWidgetItem(tableData[i][0]);
                QTableWidgetItem *item1=new QTableWidgetItem(tableData[i][1]);
                QTableWidgetItem *item2=new QTableWidgetItem(tableData[i][2]);
                QTableWidgetItem *item3=new QTableWidgetItem(tableData[i][3]);
                QTableWidgetItem *item4=new QTableWidgetItem(tableData[i][4]);
                QTableWidgetItem *item5=new QTableWidgetItem(tableData[i][5]);
                QTableWidgetItem *item6=new QTableWidgetItem(tableData[i][6]);
                QTableWidgetItem *item7=new QTableWidgetItem(tableData[i][7]);
                QTableWidgetItem *item8=new QTableWidgetItem(tableData[i][8]);
                ui->tableWidget->setItem(rowIdx,0,item0);
                ui->tableWidget->setItem(rowIdx,1,item1);
                ui->tableWidget->setItem(rowIdx,2,item2);
                ui->tableWidget->setItem(rowIdx,3,item3);
                ui->tableWidget->setItem(rowIdx,4,item4);
                ui->tableWidget->setItem(rowIdx,5,item5);
                ui->tableWidget->setItem(rowIdx,6,item6);
                ui->tableWidget->setItem(rowIdx,7,item7);
                ui->tableWidget->setItem(rowIdx,8,item8);
            }
        }
    }
}

void Page3::on_checkCall_clicked()
{
    initTableWidget();
}

void Page3::on_checkRefresh_clicked()
{
    ui->checkStatusCombox->setCurrentIndex(0);
    ui->finishStatusCombox->setCurrentText(0);
    ui->checkName->clear();
    ui->checkNo->clear();
    ui->checkWorkNubmer->clear();
    ui->checkNameLine->clear();
    initTableWidget();
}

void Page3::initOnlineWrite(){
    QSqlTableModel *model=new QSqlTableModel(this,Mes::getInstance()->db);
    model->setTable("importForm");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select();
    model->setHeaderData(0,Qt::Horizontal,QString("设备编码"));
    model->setHeaderData(1,Qt::Horizontal,QString("设备分类"));
    model->setHeaderData(2,Qt::Horizontal,QString("名称"));
    model->setHeaderData(3,Qt::Horizontal,QString("规格"));
    model->setHeaderData(4,Qt::Horizontal,QString("导入人工号"));
    model->setHeaderData(5,Qt::Horizontal,QString("库存数量"));
    model->setHeaderData(6,Qt::Horizontal,QString("设备单价"));
    model->setHeaderData(7,Qt::Horizontal,QString("供应商"));
    model->setHeaderData(8,Qt::Horizontal,QString("资产编号"));
    model->setHeaderData(9,Qt::Horizontal,QString("维保信息"));
    model->setHeaderData(10,Qt::Horizontal,QString("设备来源"));
    model->setHeaderData(11,Qt::Horizontal,QString("备注"));
    model->setHeaderData(12,Qt::Horizontal,QString("导入时间"));
    model->setHeaderData(13,Qt::Horizontal,QString("导入状态"));
    model->setHeaderData(14,Qt::Horizontal,QString("导入总数"));
    ui->tableView->setModel(model);
    initWrite();
}

void Page3::initUserRecordWrite(){
    QSqlTableModel *model=new QSqlTableModel(this,Mes::getInstance()->db);
    model->setTable("userForm");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select();
    model->setHeaderData(0,Qt::Horizontal,QString("设备编号"));
    model->setHeaderData(1,Qt::Horizontal,QString("领用人工号"));
    model->setHeaderData(2,Qt::Horizontal,QString("拥有数量"));
    model->setHeaderData(3,Qt::Horizontal,QString("超期年限"));
    model->setHeaderData(4,Qt::Horizontal,QString("经办人工号"));
    model->setHeaderData(5,Qt::Horizontal,QString("领用时间"));
    model->setHeaderData(6,Qt::Horizontal,QString("存放地点"));
    model->setHeaderData(7,Qt::Horizontal,QString("设备状态"));
    model->setHeaderData(8,Qt::Horizontal,QString("检验时间"));
    model->setHeaderData(9,Qt::Horizontal,QString("检验周期"));
    model->setHeaderData(10,Qt::Horizontal,QString("检验项目"));
    model->setHeaderData(11,Qt::Horizontal,QString("检验人工号"));
    ui->tableView1->setModel(model);
    initWrite1();
}

void Page3::initWrite(){
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->setEditTriggers(QAbstractItemView::DoubleClicked);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->horizontalHeader()->setSectionsClickable(true);
//    ui->tableView->horizontalHeader()->setHighlightSections(false);
    ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu);      // 菜单策略
    ui->tableView->horizontalHeader()->setBackgroundRole(QPalette::Background);
    connect(ui->tableView->horizontalHeader(),SIGNAL(sectionClicked(int)),this,SLOT(classifySortByColumn(int)));
//    initPopMenu();
}

void Page3::initWrite1(){
    ui->tableView1->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView1->setEditTriggers(QAbstractItemView::DoubleClicked);
    ui->tableView1->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView1->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView1->horizontalHeader()->setSectionsClickable(true);
    ui->tableView1->setContextMenuPolicy(Qt::CustomContextMenu);      // 菜单策略
    ui->tableView1->horizontalHeader()->setBackgroundRole(QPalette::Background);
    connect(ui->tableView1->horizontalHeader(),SIGNAL(sectionClicked(int)),this,SLOT(classifySortByColumn1(int)));
}

void Page3::initPopMenu2()
{
    popMenu2=new QMenu(ui->tableWidget);
    popMenu2->addAction("复制",this,SLOT(slot_copyData2()));
    popMenu2->addAction("点检历史查询",this,SLOT(slot_checkHistoryQuery2()));
    connect(ui->tableWidget,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(slotContextMenu2(QPoint)));
}

void Page3::initPopMenu1()          // 已领用设备菜单
{
    popMenu1=new QMenu(ui->tableView1);
    popMenu1->addAction("复制",this,SLOT(slot_copyData1()));
    popMenu1->addAction("保管人变更",this,SLOT(slot_userChange()));
    popMenu1->addAction("点检人变更",this,SLOT(slot_checkChange()));
//    popMenu1->addAction("增加检验项目",this,SLOT(slot_checkItemAdd()));
    popMenu1->addAction("增加或修改检验项目",this,SLOT(slot_checkItemChange()));
    popMenu1->addAction("点检历史查询",this,SLOT(slot_checkHistoryQuery()));
    popMenu1->addAction("维修历史查询",this,SLOT(slot_repairHistoryQuery()));
    popMenu1->addAction("生成二维码",this,SLOT(slot_createQRcode1()));
    connect(ui->tableView1,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(slotContextMenu1(QPoint)));
}

void Page3::slot_userChange()
{
    QString NO,workNumber;
    NO=ui->tableView1->model()->index(selectCurrentRow1,0).data().toString();
    workNumber=ui->tableView1->model()->index(selectCurrentRow1,2).data().toString();
    UserChangeDialog u(nullptr,NO,workNumber);
    u.exec();
    emit ui->tableView1->model()->dataChanged(ui->tableView1->model()->index(selectCurrentRow1,0),
        ui->tableWidget->model()->index(selectCurrentRow1,12));
}

void Page3::slot_checkChange()
{
    QString NO,workNumber,checkerWorkNumber;
    NO=ui->tableView1->model()->index(selectCurrentRow1,0).data().toString();
    workNumber=ui->tableView1->model()->index(selectCurrentRow1,2).data().toString();
    checkerWorkNumber=ui->tableView1->model()->index(selectCurrentRow1,12).data().toString();
    UserChangeDialog u(nullptr,NO,workNumber,checkerWorkNumber,true);
    u.exec();
    emit ui->tableView1->model()->dataChanged(ui->tableView1->model()->index(selectCurrentRow1,0),
        ui->tableWidget->model()->index(selectCurrentRow1,12));
}

//void Page3::slot_checkItemAdd()
//{

//}

void Page3::slot_checkItemChange()
{
    bool flag;
    QMap<QString,QVariant> userMap;
    QStringList headList;
    headList<<"NO"<<"norms"<<"useWorkNumber"<<"useAccount"<<"overTime"<<"agent"
        <<"date"<<"station"<<"threeModel"<<"noticeTime"<<"cycle"<<"items"<<"checkWorkNumber";
    for(int i=0;i<13;i++){
        QVariant tmp=ui->tableView1->model()->index(selectCurrentRow1,i).data();
        userMap.insert(headList[i],tmp);
    }
    QString threeModel=userMap["threeModel"].toString().trimmed();
    if(threeModel=="使用中" || threeModel=="点检" || threeModel=="校验" || threeModel=="保养"){
        if(Mes::getInstance()->checkIsExist(userMap["NO"].toString(),userMap["useWorkNumber"].toString(),flag)){  //判断点检or校验or保养设备存在
            if(flag){
                UseDialog u(nullptr,UseDialog::CHANGEITEMS,userMap);
                u.exec();
            }else{
                UseDialog u(nullptr,UseDialog::ADDITEMS,userMap);
                u.exec();
            }
            on_pushButton_4_clicked();
        }
    }else{
        QMessageBox::warning(NULL,"提示",QString("该设备的状态为：%1\n不支持增加或修改点检信息     ").arg(threeModel));
        return;
    }
}

void Page3::slot_checkHistoryQuery()
{
    QString NO,workNumber;
    NO=ui->tableView1->model()->index(selectCurrentRow1,0).data().toString();
    workNumber=ui->tableView1->model()->index(selectCurrentRow1,12).data().toString();
    CheckHistoryDialog c(nullptr,NO,workNumber);
    c.exec();
}

void Page3::slot_checkHistoryQuery2()
{
    QString NO,workNumber;
    NO=ui->tableWidget->model()->index(selectCurrentRow2,0).data().toString();
    workNumber=ui->tableWidget->model()->index(selectCurrentRow2,2).data().toString();
    CheckHistoryDialog c(nullptr,NO,workNumber);
    c.exec();
}

void Page3::slot_repairHistoryQuery()
{
    QString NO,workNumber;
    NO=ui->tableView1->model()->index(selectCurrentRow1,0).data().toString();
    workNumber=ui->tableView1->model()->index(selectCurrentRow1,2).data().toString();
    RepairHistoryDialog r(nullptr,NO,workNumber);
    r.exec();
}

void Page3::initPopMenu()
{

    popMenu=new QMenu(ui->tableView);
    popMenu->addAction("复制",this,SLOT(slot_copyData()));
    popMenu->addAction("生成二维码",this,SLOT(slot_createQRcode()));
    connect(ui->tableView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(slotContextMenu(QPoint)));
}

void Page3::initRead()
{
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->setEditTriggers(QAbstractItemView::DoubleClicked);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->horizontalHeader()->setSectionsClickable(true);
    ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu);      // 菜单策略
    ui->tableView->horizontalHeader()->setBackgroundRole(QPalette::Background);
    connect(ui->tableView->horizontalHeader(),SIGNAL(sectionClicked(int)),this,SLOT(classifySortByColumn(int)));
}

void Page3::initRead1()
{
    ui->tableView1->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView1->setEditTriggers(QAbstractItemView::DoubleClicked);
    ui->tableView1->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView1->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView1->horizontalHeader()->setSectionsClickable(true);
    ui->tableView1->setContextMenuPolicy(Qt::CustomContextMenu);      // 菜单策略
    ui->tableView1->horizontalHeader()->setBackgroundRole(QPalette::Background);
    connect(ui->tableView1->horizontalHeader(),SIGNAL(sectionClicked(int)),this,SLOT(classifySortByColumn1(int)));
}

void Page3::initOnlineRead()
{
    QSqlQueryModel *model = new QSqlQueryModel(ui->tableView);
    QString condition;
    condition="";
    if(ui->NO->text().trimmed()!=""){
        condition.append(QString(" and NO like '%%1%'").arg(ui->NO->text().trimmed()));
    }

    if(ui->importWorkNumber->text().trimmed()!=""){
        condition.append(QString(" and workNumber='%1'").arg(ui->importWorkNumber->text().trimmed()));
    }

    if(ui->classCombox->currentText().trimmed()!=""){
        condition.append(QString(" and className='%1'").arg(ui->classCombox->currentText().trimmed()));
    }

    if(ui->importName->text().trimmed()!=""){
        condition.append(QString(" and norms like '%%1%'").arg(ui->importName->text().trimmed()));
    }

    QString sql=QString("select top %1 * from [dm-data].[dbo].[importForm] where date!=0%2").arg(ui->historySpinBox->value()).arg(condition);
    qDebug()<<sql;
    model->setQuery(sql);
    model->setHeaderData(0,Qt::Horizontal,QString("设备编码"));
    model->setHeaderData(1,Qt::Horizontal,QString("设备分类"));
    model->setHeaderData(2,Qt::Horizontal,QString("名称"));
    model->setHeaderData(3,Qt::Horizontal,QString("规格"));
    model->setHeaderData(4,Qt::Horizontal,QString("导入人工号"));
    model->setHeaderData(5,Qt::Horizontal,QString("库存数量"));
    model->setHeaderData(6,Qt::Horizontal,QString("设备单价"));
    model->setHeaderData(7,Qt::Horizontal,QString("供应商"));
    model->setHeaderData(8,Qt::Horizontal,QString("资产编号"));
    model->setHeaderData(9,Qt::Horizontal,QString("维保信息"));
    model->setHeaderData(10,Qt::Horizontal,QString("设备来源"));
    model->setHeaderData(11,Qt::Horizontal,QString("备注"));
    model->setHeaderData(12,Qt::Horizontal,QString("导入时间"));
    model->setHeaderData(13,Qt::Horizontal,QString("导入状态"));
    model->setHeaderData(14,Qt::Horizontal,QString("导入总数"));
    ui->tableView->setModel(model);
    initRead();
}

void Page3::initUserRecordRead()
{
    QSqlQueryModel *model = new QSqlQueryModel(ui->tableView1);
    QString condition;
    condition="";
    if(ui->NO1->text().trimmed()!=""){
        condition.append(QString(" and a.NO like '%%1%'").arg(ui->NO1->text().trimmed()));
    }

    if(ui->threeModelCombox->currentText().trimmed()!=""){
        condition.append(QString(" and a.threeModel='%1'").arg(ui->threeModelCombox->currentText().trimmed()));
    }

    if(ui->userWorkNumber->text().trimmed()!=""){
        condition.append(QString(" and a.useWorkNumber='%1'").arg(ui->userWorkNumber->text().trimmed()));
    }

    if(ui->checkWorkNumber->text().trimmed()!=""){
        condition.append(QString(" and a.checkWorkNumber='%1'").arg(ui->checkWorkNumber->text().trimmed()));
    }

    if(ui->userName->text().trimmed()!=""){
        condition.append(QString(" and b.norms like '%%1%'").arg(ui->userName->text().trimmed()));
    }

    QString sql=QString("SELECT TOP %1 a.[NO],b.[norms] \
        ,a.[useWorkNumber]  \
        ,a.[useAccount] \
        ,a.[overTime]   \
        ,a.[agent]  \
        ,a.[date]   \
        ,a.[station]    \
        ,a.[threeModel] \
        ,a.[noticeTime] \
        ,a.[cycle]  \
        ,a.[items]  \
        ,a.[checkWorkNumber]    \
        FROM [dm-data].[dbo].[userForm] as a inner join [dm-data].[dbo].[importForm] as b \
        on a.NO=b.NO and a.threeModel!='变更历史'%2").arg(ui->historySpinBox1->value()).arg(condition);
    model->setQuery(sql);
    model->setHeaderData(0,Qt::Horizontal,QString("设备编号"));
    model->setHeaderData(1,Qt::Horizontal,QString("设备名称"));
    model->setHeaderData(2,Qt::Horizontal,QString("保管人工号"));
    model->setHeaderData(3,Qt::Horizontal,QString("拥有数量"));
    model->setHeaderData(4,Qt::Horizontal,QString("超期年限"));
    model->setHeaderData(5,Qt::Horizontal,QString("经办人工号"));
    model->setHeaderData(6,Qt::Horizontal,QString("领用时间"));
    model->setHeaderData(7,Qt::Horizontal,QString("存放地点"));
    model->setHeaderData(8,Qt::Horizontal,QString("设备状态"));
    model->setHeaderData(9,Qt::Horizontal,QString("检验时间"));
    model->setHeaderData(10,Qt::Horizontal,QString("检验周期"));
    model->setHeaderData(11,Qt::Horizontal,QString("检验项目"));
    model->setHeaderData(12,Qt::Horizontal,QString("检验人工号"));
    ui->tableView1->setModel(model);
    initRead1();
}

void Page3::classifySortByColumn(int col)
{
    QSqlQueryModel *model=qobject_cast<QSqlQueryModel *>(ui->tableView->model());
    QStringList l;
    l<<"[NO]"<<"[className]"<<"[norms]"<<"[model]"
            <<"[workNumber]"<<"[account]"<<"[price]"
            <<"[supplier]"<<"[assistCode]"<<"[guarantee]"
            <<"[source]"<<"[remarks]"<<"[date]"<<"[status]"<<"[orgAccount]";
    bool ascending=(ui->tableView->horizontalHeader()->sortIndicatorSection()==col
                    && ui->tableView->horizontalHeader()->sortIndicatorOrder()==Qt::DescendingOrder);
    QString order=ascending ? "asc" : "desc";
    QString sql=QString("select top %1 * from [dm-data].[dbo].[importForm] order by %2 %3").arg(ui->historySpinBox->value()).arg(l[col]).arg(order);
    model->setQuery(sql);
//    ui->tableView->reset();
}

void Page3::classifySortByColumn1(int col)
{
    QSqlQueryModel *model=qobject_cast<QSqlQueryModel *>(ui->tableView1->model());
    QStringList l;
    l<<"a.[NO]"<<"b.[norms]"<<"a.[useWorkNumber]"<<"a.[useAccount]"<<"a.[overTime]"<<"a.[agent]"
     <<"a.[date]"<<"a.[station]"<<"a.[threeModel]"<<"a.[noticeTime]"<<"a.[cycle]"
     <<"a.[items]"<<"a.[checkWorkNumber]";
    bool ascending=(ui->tableView1->horizontalHeader()->sortIndicatorSection()==col
                    && ui->tableView1->horizontalHeader()->sortIndicatorOrder()==Qt::DescendingOrder);
    QString order=ascending ? "asc" : "desc";
    QString sql=QString("SELECT TOP %1 a.[NO],b.[norms] \
        ,a.[useWorkNumber]  \
        ,a.[useAccount] \
        ,a.[overTime]   \
        ,a.[agent]  \
        ,a.[date]   \
        ,a.[station]    \
        ,a.[threeModel] \
        ,a.[noticeTime] \
        ,a.[cycle]  \
        ,a.[items]  \
        ,a.[checkWorkNumber]    \
       FROM [dm-data].[dbo].[userForm] as a inner join [dm-data].[dbo].[importForm] as b \
       on a.NO=b.NO and a.threeModel!='变更历史' order by %2 %3").arg(ui->historySpinBox1->value()).arg(l[col]).arg(order);
    model->setQuery(sql);
//    ui->tableView1->reset();
}

void Page3::on_pushButton_3_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File")," ",tr("file (*.csv)"));
    if (!fileName.isEmpty())
    {
        QString textData;
        int rows = ui->tableView->model()->rowCount();
        int columns = ui->tableView->model()->columnCount();
        for(int j=0;j<columns;j++){
            textData+=ui->tableView->model()->headerData(j,Qt::Horizontal,Qt::DisplayRole).toString();
            textData += "," ;
        }
        textData += "\n";
        for(int i = 0; i < rows; i++){
            for(int j = 0; j < columns; j++){
                if(j==11){
                    textData += ui->tableView->model()->data(ui->tableView->model()->index(i,j)).toString().replace(",",";");
                    textData += "," ;     // for .csv file format
                }else{
                    textData += ui->tableView->model()->data(ui->tableView->model()->index(i,j)).toString();
                    textData += "," ;     // for .csv file format
                }
            }
            textData += "\n";             // (optional: for new line segmentation)
        }
        // [Save to file] (header file <QFile> needed)
        // .csv
        QFile csvFile(fileName);
        if(csvFile.open(QIODevice::WriteOnly | QIODevice::Truncate)){
            QTextStream out(&csvFile);
            out << textData;
            csvFile.close();
        }
    }
}

void Page3::slotContextMenu(QPoint pos)
{
    auto index=ui->tableView->indexAt(pos);
    selectCurrentRow=index.row();
    selectCurrentColumn=index.column();
    if(index.isValid()){
        popMenu->exec(QCursor::pos());
    }
}

void Page3::slotContextMenu1(QPoint pos)
{
    auto index=ui->tableView1->indexAt(pos);
    selectCurrentRow1=index.row();
    selectCurrentColumn1=index.column();
    if(index.isValid()){
        popMenu1->exec(QCursor::pos());
    }
}

void Page3::slotContextMenu2(QPoint pos)
{
    auto index=ui->tableWidget->indexAt(pos);
    selectCurrentRow2=index.row();
    selectCurrentColumn2=index.column();
    if(index.isValid()){
        popMenu2->exec(QCursor::pos());
    }
}

void Page3::slot_createQRcode()
{
    QStringList tagList;
    for(int i=0;i<14;i++){
        QString tmp=ui->tableView->model()->index(selectCurrentRow,i).data().toString();
        qDebug()<<tmp;
        if(i==0)    {tagList<<QString("设备编码：%1").arg(tmp);continue;}
        if(i==1)    {tagList<<QString("设备分类：%1").arg(tmp);continue;}
        if(i==2)    {tagList<<QString("设备名称：%1").arg(tmp);continue;}
        if(i==3)    {tagList<<QString("设备规格：%1").arg(tmp);continue;}
        if(i==6)    {tagList<<QString("设备单价：%1").arg(tmp);continue;}
        if(i==8)    {tagList<<QString("资产编号：%1").arg(tmp);continue;}
        if(i==12)   {tagList<<QString("导入时间：%1").arg(tmp);continue;}
    }
    SaveQRCode saveDialog(tagList);
    saveDialog.exec();
}

void Page3::slot_createQRcode1()
{
    QStringList tagList;
    for(int i=0;i<8;i++){
        QString tmp=ui->tableView1->model()->index(selectCurrentRow1,i).data().toString();
        if(i==0)    {tagList<<QString("设备编号：%1").arg(tmp);continue;}
        if(i==1)    {tagList<<QString("设备名称：%1").arg(tmp);continue;}
        if(i==2)    {tagList<<QString("保管人工号：%1").arg(tmp);continue;}
        if(i==3)    {tagList<<QString("拥有数量：%1").arg(tmp);continue;}
        if(i==4)    {tagList<<QString("超期年限：%1个月").arg(tmp);continue;}
        if(i==6)    {tagList<<QString("领用时间：%1").arg(tmp);continue;}
        if(i==7)    {tagList<<QString("存放地点：%1").arg(tmp);continue;}
    }
    SaveQRCode saveDialog(tagList);
    saveDialog.exec();
}

void Page3::slot_copyData()
{
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setText(ui->tableView->model()->index(selectCurrentRow,selectCurrentColumn).data().toString());
}

void Page3::slot_copyData1()
{
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setText(ui->tableView1->model()->index(selectCurrentRow1,selectCurrentColumn1).data().toString());
}

void Page3::slot_copyData2()
{
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setText(ui->tableWidget->model()->index(selectCurrentRow2,selectCurrentColumn2).data().toString());
}

void Page3::on_modifyButton_clicked()            // 提交修改
{
    QSqlTableModel *model = dynamic_cast<QSqlTableModel *>(ui->tableView->model());
    model->database().transaction(); //开始事务操作
    if (model->submitAll()) // 提交所有被修改的数据到数据库中
    {
        model->database().commit(); //提交成功，事务将真正修改数据库数据
        QMessageBox::information(NULL,QString("提示"),QString("提交成功        "));
    } else {
        model->database().rollback(); //提交失败，事务回滚
        QMessageBox::warning(NULL, QString("错误"), QString("数据库连接失败\n")+model->lastError().text());
    }
    model->revertAll(); //撤销修改
    on_pushButton_2_clicked();
}

void Page3::on_pushButton_2_clicked()           // 刷新
{
    ui->NO->clear();
    ui->classCombox->setCurrentIndex(0);
    ui->importName->clear();
    ui->importWorkNumber->clear();
    initOnlineRead();
}
//    if(ui->twoModelCombox->currentIndex()==0){      // 查询模式
//        if(ui->useModel->currentIndex()==0){
//            initOnlineRead();
//        }else{
//            initUserRecordRead();
//        }
//    }else{
//        if(ui->useModel->currentIndex()==0){
//            initOnlineWrite();
//        }else{
//            initUserRecordWrite();
//        }
//    }


void Page3::on_pushButton_clicked()             // 查询
{
    initOnlineRead();
}
//    if(ui->twoModelCombox->currentIndex()==0){      // 查询模式
//        if(ui->useModel->currentIndex()==0){
//            initOnlineRead();
//        }else{
//            initUserRecordRead();
//        }
//    }else{
//        if(ui->useModel->currentIndex()==0){
//            initOnlineWrite();
//        }else{
//            initUserRecordWrite();
//        }
//    }


void Page3::on_twoModelCombox_currentIndexChanged(int index)
{
    if(index==0){               // 查询模式
        ui->NO->clear();
        ui->NO->setReadOnly(false);
        ui->historySpinBox->setReadOnly(false);
        ui->historySpinBox->setStyleSheet("background:transparent;");
        ui->NO->setStyleSheet("background:transparent;");
//        ui->modifyButton->setEnabled(false);
    }else{                      //  修改模式
        ui->NO->clear();
        ui->NO->setReadOnly(true);
        ui->historySpinBox->setReadOnly(true);
        ui->historySpinBox->setStyleSheet("background:rgb(238,238,238);");
        ui->NO->setStyleSheet("background:rgb(238,238,238);");
//        ui->modifyButton->setEnabled(true);
    }
    on_pushButton_2_clicked();
}

void Page3::on_useModel_currentIndexChanged(int index)
{
    on_pushButton_2_clicked();
}

void Page3::on_tabWidget_currentChanged(int index)
{
    switch (index) {
    case 0: initUserRecordRead();break;
    case 1: initOnlineRead();break;
    case 2: initTableWidget();break;
    }
}

void Page3::on_pushButton_4_clicked()
{
    initUserRecordRead();
}

void Page3::on_pushButton_5_clicked()
{
    ui->NO1->clear();
    ui->threeModelCombox->setCurrentIndex(0);
    ui->userName->clear();
    ui->userWorkNumber->clear();
    ui->checkWorkNumber->clear();
    initUserRecordRead();
}

void Page3::on_pushButton_6_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File")," ",tr("file (*.csv)"));
    if (!fileName.isEmpty())
    {
        QString textData;
        int rows = ui->tableView1->model()->rowCount();
        int columns = ui->tableView1->model()->columnCount();
        for(int j=0;j<columns;j++){
            textData+=ui->tableView1->model()->headerData(j,Qt::Horizontal,Qt::DisplayRole).toString();
            textData += "," ;
        }
        textData += "\n";
        for(int i = 0; i < rows; i++){
            for(int j = 0; j < columns; j++){
                textData += ui->tableView1->model()->data(ui->tableView1->model()->index(i,j)).toString().replace(",",";");
                textData += "," ;     // for .csv file format
            }
            textData += "\n";             // (optional: for new line segmentation)
        }
        // [Save to file] (header file <QFile> needed)
        // .csv
        QFile csvFile(fileName);
        if(csvFile.open(QIODevice::WriteOnly | QIODevice::Truncate)){
            QTextStream out(&csvFile);
            out << textData;
            csvFile.close();
        }
    }
}

void Page3::on_pushButton_7_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File")," ",tr("file (*.csv)"));
    if (!fileName.isEmpty())
    {
        QString textData;
        int rows = ui->tableWidget->model()->rowCount();
        int columns = ui->tableWidget->model()->columnCount();
        for(int j=0;j<columns;j++){
            textData+=ui->tableWidget->model()->headerData(j,Qt::Horizontal,Qt::DisplayRole).toString();
            textData += "," ;
        }
        textData += "\n";
        for(int i = 0; i < rows; i++){
            for(int j = 0; j < columns; j++){
                textData += ui->tableWidget->model()->data(ui->tableWidget->model()->index(i,j)).toString().replace(",",";");
                textData += "," ;     // for .csv file format
            }
            textData += "\n";             // (optional: for new line segmentation)
        }
        // [Save to file] (header file <QFile> needed)
        // .csv
        QFile csvFile(fileName);
        if(csvFile.open(QIODevice::WriteOnly | QIODevice::Truncate)){
            QTextStream out(&csvFile);
            out << textData;
            csvFile.close();
        }
    }
}
